package com.wx.controller;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wx.entity.SysWxuser;
import com.wx.service.SysMenuService;
import com.wx.service.SysWxuserService;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.ApplicationContextBean;
import com.zyht.common.intercepter.Token;
import com.zyht.wechat.framework.bean.InitCommonWechatEnvBean;
import com.zyht.wechat.framework.env.SystemConfigurationEvn;
import com.zyht.wechat.framework.env.WechatEnv;

@Controller
@RequestMapping("admin/wxusers")
public class SysWxUserController extends AbsManageBaseController {

	@Resource
	private SysWxuserService sysWxuserService;
	// 菜单部分
	@Resource
	private SysMenuService sysMenuService;

	@Token(remove=true)
	@RequestMapping(method=RequestMethod.POST, value = "wxuser")
	@RequiresPermissions(value = {"admin:wxusers:persis"})
	public String save(@ModelAttribute SysWxuser user,Model model,HttpServletRequest request){

		if(null == user.getId()){
			user.setCreateTime(new Date());
			this.sysWxuserService.insert(user);
		} else {
			this.sysWxuserService.updateByPK(user);
		}

		synchronized(this){
			String wxid = SystemConfigurationEvn.configuration.get("gloable_wxid");
			user = sysWxuserService.selectByWxid(wxid);
			InitCommonWechatEnvBean bean = (InitCommonWechatEnvBean) ApplicationContextBean.getBeanByName(InitCommonWechatEnvBean.class);
			if(null!=bean){
				WechatEnv.storeWxuser(bean,user);
			}
		}
		
		model.addAttribute("redirect","admin/wxusers/wxuser");
		model.addAttribute("msg","操作成功");
		return "message";
	}

	@Token(save=true)
	@RequestMapping(method=RequestMethod.GET, value = "wxuser")
	@RequiresPermissions(value = {"admin:wxusers:modify"})
	public String toAdd(Model model){
		
		SysWxuser cacheBean = WechatEnv.wxuser;
		SysWxuser user = null;
		if(WechatEnv.isWechatConfigOk()){
			user = this.sysWxuserService.selectByPrimaryKey(cacheBean.getId());
		}else{
			user = new SysWxuser();
		}
		model.addAttribute("bean",user);
		return "admin/wxusers/toAdd";
	}

}
